// AnyChat for Web SDK

/********************************************
 *				事件回调部分				*
 *******************************************/

// 异步消息通知，包括连接服务器、登录系统、进入房间等消息
function OnAnyChatNotifyMessage(dwNotifyMsg, wParam, lParam) {
	switch (dwNotifyMsg) {
		case WM_GV_CONNECT: OnAnyChatConnect(wParam, lParam); break;
		case WM_GV_LOGINSYSTEM: OnAnyChatLoginSystem(wParam, lParam); break;
		case WM_GV_ENTERROOM: OnAnyChatEnterRoom(wParam, lParam); break;
		case WM_GV_ONLINEUSER: OnAnyChatRoomOnlineUser(wParam, lParam); break;
		case WM_GV_USERATROOM: OnAnyChatUserAtRoom(wParam, lParam); break;
		case WM_GV_LINKCLOSE: OnAnyChatLinkClose(wParam, lParam); break;
		case WM_GV_MICSTATECHANGE: OnAnyChatMicStateChange(wParam, lParam); break;
		case WM_GV_CAMERASTATE: OnAnyChatCameraStateChange(wParam, lParam); break;
		case WM_GV_P2PCONNECTSTATE: OnAnyChatP2PConnectState(wParam, lParam); break;
		case WM_GV_PRIVATEREQUEST: OnAnyChatPrivateRequest(wParam, lParam); console.log(wParam, lParam); break;
		case WM_GV_PRIVATEECHO: OnAnyChatPrivateEcho(wParam, lParam); break;
		case WM_GV_PRIVATEEXIT: OnAnyChatPrivateExit(wParam, lParam); break;
		case WM_GV_USERINFOUPDATE: OnAnyChatUserInfoUpdate(wParam, lParam); break;
		case WM_GV_FRIENDSTATUS: OnAnyChatFriendStatus(wParam, lParam); break;
		default:
			break;
	}
}

// 收到文字消息
function OnAnyChatTextMessage(dwFromUserId, dwToUserId, bSecret, lpMsgBuf, dwLen) {
	DisplayTextMessage(dwFromUserId, lpMsgBuf);
	console.log(dwFromUserId, lpMsgBuf);
}

// 收到透明通道传输数据
function OnAnyChatTransBuffer(dwUserId, lpBuf, dwLen) {
	alert("收到:" + dwUserId + "用户发送过来的透明通道数据数据：" + lpBuf);
	console.log("收到:" + dwUserId + "用户发送过来的透明通道数据数据：" + lpBuf);
	console.log("收到长度：" + lpBuf.length);
}

// 收到透明通道（扩展）传输数据
function OnAnyChatTransBufferEx(dwUserId, lpBuf, dwLen, wParam, lParam, dwTaskId) {
	alert("收到:" + dwUserId + "用户发送过来的扩展透明通道数据数据：" + lpBuf);
	console.log("收到:" + dwUserId + "用户发送过来的扩展透明通道数据数据：" + lpBuf);
	console.log("收到长度：" + lpBuf.length);
}

// 文件传输完成通知
function OnAnyChatTransFile(dwUserId, lpFileName, lpTempFilePath, dwFileLength, wParam, lParam, dwTaskId) {

	//alert("收到文件:"+dwUserId+"用户发送过来的文件："+"接收路径在："+lpTempFilePath);
	console.log("收到文件:" + dwUserId + "用户发送过来的文件：" + "接收路径在：" + lpTempFilePath);
}

// 系统音量改变通知
function OnAnyChatVolumeChange(device, dwCurrentVolume) {

}

// 收到服务器发送的SDK Filter数据
function OnAnyChatSDKFilterData(lpBuf, dwLen) {
	console.log(lpBuf, dwLen);
}

// 收到录像或拍照完成事件
function OnAnyChatRecordSnapShot(dwUserId, lpFileName, dwParam, bRecordType) {
	//console.log(bRecordType)
	//console.log("1111")

	if (bRecordType == 0) {
		//alert("抓拍成功，文件路径是："+lpFileName);
		//console.log("抓拍成功，文件路径是："+lpFileName);
	}
	else if (bRecordType == 1) {
		//alert("录像成功，文件路径是："+lpFileName);
		//console.log("录像成功，文件路径是："+lpFileName);
	}
}
function OnAnyChatRecordSnapShotEx(dwUserId, lpFileName, dwElapse, dwFlags, dwParam, lpUserStr) {
	//AddLog('OnAnyChatRecordSnapShotEx(' + dwUserId + ',' + lpFileName + ',' + dwElapse + ',' + dwFlags + ',' + dwParam + ',' + lpUserStr + ')', LOG_TYPE_EVENT);
	//AddLog("录像/拍照成功，文件路径为：" + lpFileName , LOG_TYPE_NORMAL);
	DisplayTextMessage(-1, lpFileName);

	var VADCtrol = 1;
	BRAC_SetSDKOption(BRAC_SO_AUDIO_VADCTRL, VADCtrol);

	var html = "文件路径为：" + lpFileName;
	$("#dialog-confirm").html(html);
	$("#dialog-confirm").dialog({
		modal: true,
		width: 600,
		buttons: {
			"确定": function () {
				$(this).dialog("close");
				$("#dialog-confirm").html("");
			}
		}
	});

	$("#dialog-confirm").parent().append("<iframe frameborder=0 scrolling=no style=\"background-color:transparent; position: absolute; z-index: -1; width: 100%; height: 100%; top: 0;left:0;\"></iframe>");

	//$.messager.alert("提示","文件路径为：" + lpFileName);
	//$("#serviceInfoTable tr:eq(5) td:eq(0)").text("文件路径为：" + lpFileName);
}

var lpFileNames = ""
// 收到录像或拍照完成事件（扩展2：增加errorcode）
function OnAnyChatRecordSnapShotEx2(dwUserId, dwErrorCode, lpFileName, dwElapse, dwFlags, dwParam, lpUserStr) {
	if(lpFileNames !== ""){
		lpFileNames=""
	}
	console.log("录制回调lpFileName",lpFileName);
	console.log("录制回调dwFlags",dwFlags);
	console.log("录制回调 dwElapse",dwElapse);
	console.log("录制回调 dwUserId",dwUserId);

	if (dwErrorCode !== 0) {
		DisplayTextMessage(-1, "录像异常，错误码：" + dwErrorCode);
	}
	lpFileNames = lpFileName
}

// AnyChatCoreSDK异步事件
function OnAnyChatCoreSDKEvent(dwEventType, lpEventJsonStr) {
	//console.log("异步通知：" +"Type:" +dwEventType+":"+lpEventJsonStr);
	//DisplayTextMessage(-1, "异步通知：" +"Type:" +dwEventType+":"+lpEventJsonStr);
	//	var myDate1 = new Date();

	//	console.log(myDate1+"AnyChatCoreSDK异步事件:");

	//console.log("事件类型："+dwEventType+"；\n事件内容:"+lpEventJsonStr);

	/*if(dwEventType == 2){
		
		console.log("连接保持事件通知");
		var myDate = new Date();
		//获取日期与时间
		//console.log("Time:"+myDate.toLocaleString());
	
		//console.log("OnAnyChatCoreSDKEvent{")
		//console.log("dwEventType:"+dwEventType);
		//console.log("lpEventJsonStr:"+lpEventJsonStr);
		//console.log("}");
		
		//console.log("Time:"+myDate.toLocaleString()+" ,length:"+lpEventJsonStr.length);
	}*/
	//
	if (dwEventType == 4) {
		//AddLog("异步通知：" +"Type:" +dwEventType+":"+lpEventJsonStr, LOG_TYPE_EVENT);
		console.log("录像状态事件：" + "Type:" + dwEventType + ":" + lpEventJsonStr);
	}

	if (dwEventType == 13) {
		//AddLog("异步通知：" +"Type:" +dwEventType+":"+lpEventJsonStr, LOG_TYPE_EVENT);
		console.log("录像状态事件：" + "Type:" + dwEventType + ":" + lpEventJsonStr);
	}

	if (dwEventType === 100) {

		console.log("业务缓冲区控制-异步回调事件通知");
		var myDate = new Date();
		//获取日期与时间
		//console.log("Time:"+myDate.toLocaleString());

		//console.log("OnAnyChatCoreSDKEvent{")
		//console.log("dwEventType:"+dwEventType);
		//console.log("lpEventJsonStr:"+lpEventJsonStr);
		//console.log("}");

		//console.log("Time:"+myDate.toLocaleString()+" ,length:"+lpEventJsonStr.length);
	}
	//
	if (dwEventType === 104) {

		console.log("连接用户自定义服务器能力-异步回调事件通知");
		var myDate = new Date();
		//获取日期与时间
		//console.log("Time:"+myDate.toLocaleString());

		console.log("OnAnyChatCoreSDKEvent{")
		console.log("dwEventType:" + dwEventType);
		console.log("lpEventJsonStr:" + lpEventJsonStr);
		console.log("}");

		console.log("Time:" + myDate.toLocaleString() + " ,length:" + lpEventJsonStr.length);
	}

}



/********************************************
 *		AnyChat SDK核心业务流程				*
 *******************************************/

// 客户端连接服务器，bSuccess表示是否连接成功，errorcode表示出错代码
function OnAnyChatConnect(bSuccess, errorcode) {
	AddLog("OnAnyChatConnect(errorcode=" + errorcode + ")", LOG_TYPE_EVENT);
	if (errorcode == 0) {

	}
	else {
		DisplayLoadingDiv(false);
	}
}

// 客户端登录系统，dwUserId表示自己的用户ID号，errorcode表示登录结果：0 成功，否则为出错代码，参考出错代码定义
function OnAnyChatLoginSystem(dwUserId, errorcode) {
	DisplayLoadingDiv(false);
	AddLog("OnAnyChatLoginSystem(userid=" + dwUserId + ", errorcode=" + errorcode + ")", LOG_TYPE_EVENT);
	if (errorcode == 0) {
		mSelfUserId = dwUserId;
		ShowHallDiv(true);
	} else {
		ShowHallDiv(false);
	}

}

// 客户端进入房间，dwRoomId表示所进入房间的ID号，errorcode表示是否进入房间：0成功进入，否则为出错代码
function OnAnyChatEnterRoom(dwRoomId, errorcode) {
	DisplayLoadingDiv(false);
	AddLog("OnAnyChatEnterRoom(roomid=" + dwRoomId + ", errorcode=" + errorcode + ")", LOG_TYPE_EVENT);
	if (errorcode == 0) {
		ShowRoomDiv(true);

		var BRAC_SO_LOCALVIDEO_WATERMARK = 113;   ///< 视频迭加水印控制（图片、文字）
		var jsonmark = {
			"textoverlay": {
				"fontcolor": "0xffffff",
				"alpha": 100,
				"posx": 5,
				"posy": 5,
				"fontsize": 15,
				"useservertime": 1,
				"text": "test [timestamp] 实时水印"
			},
			"watermark": {
				"alpha": 10,
				"posx": 10,
				"posy": 10,
				"overlayimgwidth": 32,
				"overlayimgheight": 32,
				"imagepath": "D:\\元气壁纸缓存\\img\\4add7f57b8013fdda379730a45d9d38a.jpg"
			}
		};
		var jsonMARK = JSON.stringify(jsonmark);
		var errorcode = BRAC_SetUserStreamInfo(-1, 0, BRAC_SO_LOCALVIDEO_WATERMARK, jsonMARK);
		//var errorcode = BRAC_SetSDKOption(BRAC_SO_LOCALVIDEO_WATERMARK,jsonMARK);



		console.log("设置水印");


		RoomUserListControl(mSelfUserId, true);		// 将自己插入用户列表
		BRAC_UserCameraControl(mSelfUserId, 1); 	// 打开本地视频
		BRAC_UserSpeakControl(mSelfUserId, 1); 		// 打开本地语音

		meiyan_level();

		ShowNotifyMessage("Welcome use AnyChat, successfully enter the room:" + dwRoomId, NOTIFY_TYPE_SYSTEM);
		// 设置本地视频显示位置
		BRAC_SetVideoPos(mSelfUserId, GetID("AnyChatLocalVideoDiv"), "ANYCHAT_VIDEO_LOCAL");
		//BRAC_SetVideoPos(mSelfUserId, GetID("AnyChatRemoteVideoDiv"), "ANYCHAT_VIDEO_REMOTE");
		//BRAC_SetVideoPos(0, GetID("AnyChatLocalVideoDiv"), "ANYCHAT_VIDEO_LOCAL");
		// 设置远程视频显示位置（没有关联到用户，只是占位置）
		BRAC_SetVideoPos(0, GetID("AnyChatRemoteVideoDiv"), "ANYCHAT_VIDEO_REMOTE");
		//BRAC_SetVideoPos(mSelfUserId, GetID("AnyChatRemoteVideoDiv"), "ANYCHAT_VIDEO_REMOTE");

		//mRefreshVolumeTimer = setInterval(function () {
		//GetID("LocalAudioVolume").style.width = GetID("AnyChatLocalVideoDiv").offsetHeight * BRAC_QueryUserStateInt(mSelfUserId, BRAC_USERSTATE_SPEAKVOLUME) / 100 + "px";
		//	if(mTargetUserId != -1)
		//GetID("RemoteAudioVolume").style.width = GetID("AnyChatRemoteVideoDiv").offsetHeight * BRAC_QueryUserStateInt(mTargetUserId, BRAC_USERSTATE_SPEAKVOLUME) / 100 + "px";
		//	else
		//		GetID("RemoteAudioVolume").style.width = "0px";
		// }, 100);
		var mRefreshBrateTimer = setInterval(function () {

			//GetID("div_localstreamname"+k).innerHTML = k+"路视频码率："+parseInt(BRAC_GetUserStreamInfoInt(-1,k,BRAC_STREAMINFO_VIDEOBITRATE)/1000)+"KBps";//视频码率、音频码率 +"；\n"+k+"路音频码率："+parseInt(BRAC_GetUserStreamInfoInt(-1,k,BRAC_STREAMINFO_AUDIOBITRATE)/1000)+"Kbps"

			//console.log("用户:"+mTargetUserId+"-音频码率："+BRAC_QueryUserStateInt(mTargetUserId,10)/1000+"Kbps");
			//console.log("本人:-1"+"-音频码率："+BRAC_QueryUserStateInt(-1,10)/1000+"Kbps");


			//console.log("用户:"+mTargetUserId+"-音频码率："+BRAC_GetUserStreamInfoInt(mTargetUserId, 0, BRAC_STREAMINFO_AUDIOBITRATE)/1000+"Kbps");
			//console.log("本人:-1"+"-音频码率："+BRAC_GetUserStreamInfoInt(-1, 0, BRAC_STREAMINFO_AUDIOBITRATE)/1000+"Kbps");

		}, 1000);

	} else {

	}


	//var tag=BRAC_RECORD_FLAGS_VIDEO+BRAC_RECORD_FLAGS_AUDIO+BRAC_RECORD_FLAGS_MIXVIDEO+BRAC_RECORD_FLAGS_MIXAUDIO+BRAC_RECORD_FLAGS_STEREO;
	//setTimeout(BRAC_StreamRecordCtrl(-1,1,tag,0), 5000);
}

// 收到当前房间的在线用户信息，进入房间后触发一次，dwUserCount表示在线用户数（包含自己），dwRoomId表示房间ID
function OnAnyChatRoomOnlineUser(dwUserCount, dwRoomId) {
	AddLog("OnAnyChatRoomOnlineUser(count=" + dwUserCount + ", roomid=" + dwRoomId + ")", LOG_TYPE_EVENT);
	var useridlist = BRAC_GetOnlineUser();
	for (var i = 0; i < useridlist.length; i++) {
		RoomUserListControl(useridlist[i], true);
	}
	// 请求其中一个用户的音视频
	for (var k = 0; k < useridlist.length; k++) {
		if (useridlist[k] == mSelfUserId)
			continue;
		RequestOtherUserVideo(useridlist[k]);
		break;
	}
}

// 用户进入（离开）房间，dwUserId表示用户ID号，bEnterRoom表示该用户是进入（1）或离开（0）房间
function OnAnyChatUserAtRoom(dwUserId, bEnterRoom) {
	AddLog("OnAnyChatUserAtRoom(userid=" + dwUserId + ", benter=" + bEnterRoom + ")", LOG_TYPE_EVENT);
	RoomUserListControl(dwUserId, bEnterRoom ? true : false);
	if (bEnterRoom == 1) {
		ShowNotifyMessage(BRAC_GetUserName(dwUserId) + "&nbspenter room!", NOTIFY_TYPE_NORMAL);
		if (mTargetUserId == -1)						// 默认打开一个用户的音视频
			RequestOtherUserVideo(dwUserId);
	}
	else {
		ShowNotifyMessage(BRAC_GetUserName(dwUserId) + "&nbspleave room!", NOTIFY_TYPE_NORMAL);
		if (dwUserId == mTargetUserId) {			// 当前被请求的用户离开房间，默认请求房间中其它用户的音视频
			var bRequestOtherUser = false;
			var useridlist = BRAC_GetOnlineUser();
			for (var k = 0; k < useridlist.length; k++) {
				if (useridlist[k] == mSelfUserId)
					continue;
				RequestOtherUserVideo(useridlist[k]);
				bRequestOtherUser = true;
				break;
			}
			if (!bRequestOtherUser) {				// 如果没有其它用户在线，则清除状态
				mTargetUserId = -1;
				BRAC_SetVideoPos(0, GetID("AnyChatRemoteVideoDiv"), "ANYCHAT_VIDEO_REMOTE");
				//BRAC_SetVideoPos(0, GetID("AnyChatLocalVideoDiv"), "ANYCHAT_VIDEO_LOCAL");
			}
		}
	}
	DisplayScroll("room_div_userlist");
}

// 网络连接已关闭，该消息只有在客户端连接服务器成功之后，网络异常中断之时触发，reason表示连接断开的原因
function OnAnyChatLinkClose(reason, errorcode) {
	AddLog("OnAnyChatLinkClose(reason=" + reason + ", errorcode=" + errorcode + ")", LOG_TYPE_EVENT);
	DisplayLoadingDiv(false);
	ShowRoomDiv(false);
	ShowHallDiv(false);
	ShowLoginDiv(true);
}

// 用户的音频设备状态变化消息，dwUserId表示用户ID号，State表示该用户是否已打开音频采集设备（0：关闭，1：打开）
function OnAnyChatMicStateChange(dwUserId, State) {

}

// 用户摄像头状态发生变化，dwUserId表示用户ID号，State表示摄像头的当前状态（0：没有摄像头，1：有摄像头但没有打开，2：打开）
function OnAnyChatCameraStateChange(dwUserId, State) {
	if (State == 0) GetID(dwUserId + "_CameraTag").src = "";
	if (State == 1) GetID(dwUserId + "_CameraTag").src = "./images/advanceset/camera_false.png";
	if (State == 2) GetID(dwUserId + "_CameraTag").src = "./images/advanceset/camera_true.png";
}

// 本地用户与其它用户的P2P网络连接状态发生变化，dwUserId表示其它用户ID号，State表示本地用户与其它用户的当前P2P网络连接状态（0：没有连接，1：仅TCP连接，2：仅UDP连接，3：TCP与UDP连接）
function OnAnyChatP2PConnectState(dwUserId, State) {

}

// 用户发起私聊请求，dwUserId表示发起者的用户ID号，dwRequestId表示私聊请求编号，标识该请求
function OnAnyChatPrivateRequest(dwUserId, dwRequestId) {
	console.log(dwUserId, dwRequestId);
}

// 用户回复私聊请求，dwUserId表示回复者的用户ID号，errorcode为出错代码
function OnAnyChatPrivateEcho(dwUserId, errorcode) {

}

// 用户退出私聊，dwUserId表示退出者的用户ID号，errorcode为出错代码
function OnAnyChatPrivateExit(dwUserId, errorcode) {

}

// 视频通话消息通知回调函数
function OnAnyChatVideoCallEvent(dwEventType, dwUserId, dwErrorCode, dwFlags, dwParam, szUserStr) {
	AddLog("OnAnyChatVideoCallEvent(dwEventType=" + dwEventType + ", dwUserId=" + dwUserId + ", dwErrorCode=" + dwErrorCode + ", dwFlags=" + dwFlags + ", dwParam=" + dwParam + ", szUserStr=" + szUserStr + ")", LOG_TYPE_EVENT);

}

// 用户信息更新通知，dwUserId表示用户ID号，dwType表示更新类别
function OnAnyChatUserInfoUpdate(dwUserId, dwType) {
	AddLog("OnAnyChatUserInfoUpdate(dwUserId=" + dwUserId + ", dwType=" + dwType + ")", LOG_TYPE_EVENT);
}

// 好友在线状态变化，dwUserId表示好友用户ID号，dwStatus表示用户的当前活动状态：0 离线， 1 上线
function OnAnyChatFriendStatus(dwUserId, dwStatus) {
	AddLog("OnAnyChatFriendStatus(dwUserId=" + dwUserId + ", dwStatus=" + dwStatus + ")", LOG_TYPE_EVENT);

}


//业务对象事件通知
function OnAnyChatObjectEvent(dwObjectType, dwObjectId, dwEventType, dwParam1, dwParam2, dwParam3, dwParam4, strParam) {
	//AddLog("OnAnyChatObjectEvent(dwObjectType=" + dwObjectType + ", dwObjectId=" + dwObjectId +  ", dwEventType=" + dwEventType + ")", LOG_TYPE_EVENT);
	//refreshAgentServiceInfo();
	//console.log("业务对象事件通知："+dwEventType);
	switch (dwEventType) {
		case ANYCHAT_OBJECT_EVENT_UPDATE: OnAnyChatObjectUpdate(dwObjectType, dwObjectId); break;
		case ANYCHAT_OBJECT_EVENT_SYNCDATAFINISH: OnAnyChatObjectSyncDataFinish(dwObjectType, dwObjectId); break;
		case ANYCHAT_AREA_EVENT_ENTERRESULT: OnAnyChatEnterAreaResult(dwObjectType, dwObjectId, dwParam1); break;
		case ANYCHAT_AREA_EVENT_LEAVERESULT: OnAnyChatLeaveAreaResult(dwObjectType, dwObjectId, dwParam1); break;
		case ANYCHAT_AREA_EVENT_STATUSCHANGE: OnAnyChatAreaStatusChange(dwObjectType, dwObjectId, dwParam1); break;
		case ANYCHAT_QUEUE_EVENT_STATUSCHANGE: OnAnyChatQueueStatusChanged(dwObjectType, dwObjectId); break;
		case ANYCHAT_QUEUE_EVENT_ENTERRESULT: OnAnyChatEnterQueueResult(dwObjectType, dwObjectId, dwParam1); break;
		case ANYCHAT_QUEUE_EVENT_LEAVERESULT: OnAnyChatLeaveQueueResult(dwObjectType, dwObjectId, dwParam1); break;
		case ANYCHAT_AGENT_EVENT_STATUSCHANGE: OnAnyChatAgentStatusChanged(dwObjectType, dwObjectId, dwParam1); break;
		case ANYCHAT_AGENT_EVENT_SERVICENOTIFY: OnAnyChatServiceStart(dwParam1, dwParam2, dwParam3, strParam); break;
		case ANYCHAT_AGENT_EVENT_WAITINGUSER: OnAnyChatAgentWaitingUser(); break;
		case ANYCHAT_QUEUE_EVENT_USERINFOLISTCHG: OnAnyChatAgentUserInfoListChg(dwObjectType, dwObjectId); break;
		case ANYCHAT_AGENT_EVENT_SERVICETIMEOUT: OnAnyChatServiceTimeout(dwObjectType, dwObjectId, dwEventType, dwParam1, dwParam2, dwParam3, dwParam4, strParam); break;
		default:
			break;
	}
}
function OnAnyChatServiceTimeout(dwObjectType, dwObjectId, dwEventType, dwParam1, dwParam2, dwParam3, dwParam4, strParam) {
	AddLog("OnAnyChatServiceTimeout(dwObjectType=" + dwObjectType + ", dwObjectId=" + dwObjectId + ", dwEventType=" + dwEventType + ")", LOG_TYPE_EVENT);
	AddLog('OnAnyChatServiceTimeout(' + dwParam1 + ',' + dwParam2 + ',' + dwParam3 + ',' + dwParam4 + ',' + strParam + ')', LOG_TYPE_EVENT);
	alert("ANYCHAT_AGENT_EVENT_SERVICETIMEOUT!");
}
//队列用户信息更新 dwObjectId表示用户信息有更新的队列ID
function OnAnyChatAgentUserInfoListChg(dwObjectType, dwObjectId) {
	//console.log("本营业厅队列-"+dwObjectId+"用户信息有更新：");
	var queueName = BRAC_ObjectGetStringValue(ANYCHAT_OBJECT_TYPE_QUEUE, dwObjectId, ANYCHAT_QUEUE_INFO_USERINFOLIST);
	console.log(dwObjectId + ":***队列相关的信息BRAC_ObjectGetStringValue：" + queueName + ";");
}

//业务对象数据更新事件
function OnAnyChatObjectUpdate(dwObjectType, dwObjectId) {
	var str = null;
	//AddLog('OnAnyChatObjectUpdate(' + dwObjectType + ',' + dwObjectId + ')', LOG_TYPE_EVENT);

	if (dwObjectType == ANYCHAT_OBJECT_TYPE_AREA) {
		areaIdArray[areaArrayIdx] = dwObjectId;
		areaArrayIdx++;
	} else if (dwObjectType == ANYCHAT_OBJECT_TYPE_QUEUE) {

	} else if (dwObjectType == ANYCHAT_OBJECT_TYPE_AGENT) {

	}
}

//业务对象同步完成事件
function OnAnyChatObjectSyncDataFinish(dwObjectType, dwObjectId) {
	AddLog('OnAnyChatObjectSyncDataFinish(' + dwObjectType + ',' + dwObjectId + ')', LOG_TYPE_EVENT);

	if (dwObjectType == ANYCHAT_OBJECT_TYPE_AREA) {
		mCurrentStatus = CLIENT_STATUS_AREA;
		showSerivceArea();
	}
}

// 进入服务区域通知事件
function OnAnyChatEnterAreaResult(dwObjectType, dwObjectId, dwErrorCode) {
	AddLog('OnAnyChatEnterAreaResult(' + dwObjectType + ',' + dwObjectId + ',' + dwErrorCode + ')', LOG_TYPE_EVENT);
	if (dwErrorCode == 0) {
		colorIdx = 0;
		// 进入服务区域成功
		if (userType == USER_TYPE_CLIENT) {//客户
			mCurrentStatus = CLIENT_STATUS_QUEUE;

			//获取队列
			var queueList = BRAC_ObjectGetIdList(ANYCHAT_OBJECT_TYPE_QUEUE);
			if (queueList.length == 0) {
				$("#LOADING_GREY_DIV").hide(); //隐藏蒙层
				ForSession("营业厅中没有可用的队列...", true);
				//离开该营业厅
				leaveFlag = BRAC_ObjectControl(ANYCHAT_OBJECT_TYPE_AREA, dwObjectId, ANYCHAT_AREA_CTRL_USERLEAVE, dwErrorCode, 0, 0, 0, "");
				return;
			}
			for (var i in queueList) {
				var queueListId = parseInt(queueList[i]);
				/**获取队列名称*/
				var queueName = BRAC_ObjectGetStringValue(ANYCHAT_OBJECT_TYPE_QUEUE, queueListId, ANYCHAT_OBJECT_INFO_NAME);
				/**获取队列排队人数*/
				var queueLength = BRAC_ObjectGetIntValue(ANYCHAT_OBJECT_TYPE_QUEUE, queueListId, ANYCHAT_QUEUE_INFO_LENGTH);
				queueLength = queueLength < 0 ? 0 : queueLength;
				/**获取队列信息*/
				var queueInfo = BRAC_ObjectGetStringValue(ANYCHAT_OBJECT_TYPE_QUEUE, queueListId, ANYCHAT_OBJECT_INFO_DESCRIPTION);
				var attributeValue = BRAC_ObjectGetIntValue(ANYCHAT_OBJECT_TYPE_QUEUE, queueListId, ANYCHAT_OBJECT_INFO_ATTRIBUTE);

				var queueSkillName = "";
				//获取队列所属技能分组
				var skillList = getFlagList(attributeValue);
				for (var skillValue in skillList) {
					var arrayId = getZhiShu(skillValue);
					if (arrayId >= skillsArray.length) {
						arrayId = 0;
					}
					if (queueSkillName == "") {
						queueSkillName = skillsArray[arrayId];
					} else {
						queueSkillName = queueSkillName + "," + skillsArray[arrayId];
					}
				}

				$("#LOADING_GREY_DIV").hide(); //隐藏蒙层
				$('#poptip li[areaId]').hide(); //隐藏服务厅
				$("#enterRoom h2").text(queueListName);
				var liObject = $('<li class="queue-item" queueid="' + queueListId + '">' +
					'<span class="queue-item-layout">' +
					'<span class="queue-item-layout-title">' + queueName + '</span>' +
					'<span class="queue-item-layout-desc">' + queueInfo + '</span>' +
					'<span class="queue-item-layout-desc">' + '所属分组：' + queueSkillName + '</span>' +
					'<span class="queue-item-layout-desc">' + '当前排队人数：<strong>' + queueLength + " 人" + '</strong></span>' +
					'</span>' +
					'<a class="queue-item-link"><img class="queue-item-pic" src="./img/queue.png" /></a>' +
					'<span class="queue-item-layout-btn">' + '<a class="btn btn-info">立即办理</a>' + '</span>' +
					'</li>');
				//liObject.css("background-color", colorQueueArray[colorIdx]);
				$("#poptip").append(liObject);
				colorIdx++;
				if (colorIdx == 3) {
					colorIdx = 0;
				}
			}
		}

		//坐席

		if (userType == USER_TYPE_AGENT) {

			$("#LOADING_GREY_DIV").hide(); //隐藏等待蒙层
			mCurrentStatus = AGENT_STATUS_SERVICE;
			console.log("-------------进入服务区域通知--------------");
			refreshAgentServiceInfo();
			var queueList = BRAC_ObjectGetIdList(ANYCHAT_OBJECT_TYPE_QUEUE);
			//AddLog("关联队列BRAC_ObjectGetIdList(" + queueList + ")",LOG_TYPE_EVENT);//打印队列信息
			//console.log("关联队列BRAC_ObjectGetIdList:" + queueList.length + ";");//打印队列信息
			//console.log("关联队列BRAC_ObjectGetIdList:" + queueList + ";");
			//坐席进入营业厅的初始状态为"关闭"
			var errorcode = BRAC_ObjectControl(ANYCHAT_OBJECT_TYPE_AGENT, mSelfUserId, ANYCHAT_AGENT_CTRL_SERVICESTATUS, ANYCHAT_AGENT_STATUS_CLOSEED, 0, 0, 0, "");
			AddLog("BRAC_ObjectControl(" + ANYCHAT_OBJECT_TYPE_AGENT + "," + mSelfUserId + "," + ANYCHAT_AGENT_CTRL_SERVICESTATUS + "," + ANYCHAT_AGENT_STATUS_CLOSEED + ",0,0,0,''" + ")=" + errorcode, LOG_TYPE_API);

			//	        setInterval(
			//					function() {
			//						refreshAgentServiceInfo();
			//			}, 5000);			
		}
	}
}

// 离开服务区域通知事件
function OnAnyChatLeaveAreaResult(dwObjectType, dwObjectId, dwErrorCode) {
	AddLog('OnAnyChatLeaveAreaResult(' + dwObjectType + ',' + dwObjectId + ',' + dwErrorCode + ')', LOG_TYPE_EVENT);
	if (userType == USER_TYPE_CLIENT) {
		mCurrentStatus = CLIENT_STATUS_AREA;
	}
	if (userType == USER_TYPE_AGENT) {
		mCurrentStatus = AGENT_STATUS_AREA;
		//关闭坐席端的本地视频
		//startVideo(mSelfUserId, GetID("localVideoPos"), "ANYCHAT_VIDEO_LOCAL",0);	
		BRAC_UserCameraControl(mSelfUserId, 0);
	}

}

//营业厅状态变化
function OnAnyChatAreaStatusChange(dwObjectType, dwObjectId, dwErrorCode) {
	AddLog('OnAnyChatAreaStatusChange(' + dwObjectType + ',' + dwObjectId + ',' + dwErrorCode + ')', LOG_TYPE_EVENT);

	if (userType == USER_TYPE_AGENT) {
		console.log("-----------营业厅状态变化------------------");
		refreshAgentServiceInfo();
	}
}

// 队列状态变化
function OnAnyChatQueueStatusChanged(dwObjectType, dwObjectId) {
	AddLog('OnAnyChatQueueStatusChanged(' + dwObjectType + ',' + dwObjectId + ')', LOG_TYPE_EVENT);
	console.log('OnAnyChatQueueStatusChanged(' + dwObjectType + ',' + dwObjectId + ')');
	if (userType == USER_TYPE_AGENT) {
		console.log("--------------队列状态变化-----------------");
		refreshAgentServiceInfo();
		refreshQueueInfoDisplay(dwObjectId);
	}

	if (queueid == dwObjectId) {
		refreshUserWaitingInfo(dwObjectId);
	}

	//refreshUserWaitingInfo(dwObjectId);
	//refreshQueueInfoDisplay(dwObjectId);//2022
}

// 本地用户进入队列结果
function OnAnyChatEnterQueueResult(dwObjectType, dwObjectId, dwErrorCode) {
	AddLog('OnAnyChatEnterQueueResult(' + dwObjectType + ',' + dwObjectId + ',' + dwErrorCode + ')', LOG_TYPE_EVENT);
	currentSelectedQueueName = BRAC_ObjectGetStringValue(ANYCHAT_OBJECT_TYPE_QUEUE, dwObjectId, ANYCHAT_OBJECT_INFO_NAME);
	$("#enterRoom h2").text(currentSelectedQueueName + " - 服务窗口");
	isShowReturnBtn(false);

	$("#LOADING_GREY_DIV").hide();//隐藏等待蒙层
	$("#poptip").hide(); //隐藏队列
	$("#queueMsg1").show(); //重置显示排队信息
	$("#queueMsg2").hide(); //隐藏呼叫信息
	$(".callBox").show(); //显示呼叫信息窗口
	$("#queueMsg1 strong:eq(2)").text(0); //清零排队时间
	clearInterval(waitTimeSet);
	waitTimeSet = setInterval(function () {
		var time = formatSeconds(BRAC_ObjectGetIntValue(ANYCHAT_OBJECT_TYPE_QUEUE, queueid, ANYCHAT_QUEUE_INFO_WAITTIMESECOND));
		$("#queueMsg1 strong:eq(2)").text(time);
	}, 1000);

	if (userType == USER_TYPE_CLIENT) {
		mCurrentStatus = CLIENT_STATUS_QUEUEING;
	}
}

// 本地用户离开队列结果
function OnAnyChatLeaveQueueResult(dwObjectType, dwObjectId, dwErrorCode) {
	AddLog('OnAnyChatLeaveQueueResult(' + dwObjectType + ',' + dwObjectId + ',' + dwErrorCode + ')', LOG_TYPE_EVENT);
	if (dwErrorCode == 0) isShowReturnBtn(true);
	currentSelectedQueueName = "";

	if ($(".callBox").css("display") != "block") {
		$("#LOADING_GREY_DIV").hide();//隐藏等待蒙层
		$("#poptip").show();
		$("#poptip li[queueid]").show(); //显示队列列表
	}

	if (userType == USER_TYPE_CLIENT) {
		mCurrentStatus = CLIENT_STATUS_QUEUE;
	}
}

// 坐席状态变化
function OnAnyChatAgentStatusChanged(dwObjectType, dwObjectId, dwParam1) {
	AddLog('OnAnyChatAgentStatusChanged(' + dwObjectType + ',' + dwObjectId + ',' + dwParam1 + ')', LOG_TYPE_EVENT);
	if (dwObjectType == ANYCHAT_OBJECT_TYPE_AGENT && currentAgentID == dwObjectId) {
		if (dwParam1 == ANYCHAT_AGENT_STATUS_WAITTING) {
			console.log("------------坐席状态变化--------------");
			refreshAgentServiceInfo();

			startServiceTag = false;
			$("#LOADING_GREY_DIV span").show();
			refreshServicedUserInfo(-1);

			isShowReturnBtn(true);

			$("#serviceInfoTable tr:eq(3) td:eq(1)").text("准备");
			$("#startService").attr("disabled", false);
			$("#agentLeave").attr("disabled", false);
			$("#stopService").attr("disabled", true);
			$("#remoteControlBtn").attr("disabled", true);
			$("#shareDesktopBtn").attr("disabled", true);
			$("#snapshotBtn").attr("disabled", true);
			$("#recordBtn").attr("disabled", true);

			$("#serviceInfoTable tr:eq(5) td:eq(0)").text("");

		} else if (dwParam1 == ANYCHAT_AGENT_STATUS_WORKING) {
			startServiceTag = true;
			$("#serviceInfoTable tr:eq(3) td:eq(1)").text("忙碌");
			refreshServicedUserInfo(mTargetUserId);
			$("#startService").attr("disabled", true);
			$("#agentLeave").attr("disabled", true);
			$("#stopService").attr("disabled", false);
			$("#remoteControlBtn").attr("disabled", true);
			$("#shareDesktopBtn").attr("disabled", false);
			$("#snapshotBtn").attr("disabled", false);
			$("#recordBtn").attr("disabled", false);
		} else if (dwParam1 == ANYCHAT_AGENT_STATUS_PAUSED) {
			startServiceTag = false;
			$("#serviceInfoTable tr:eq(3) td:eq(1)").text("离开");
			$("#startService").attr("disabled", false);
			$("#agentLeave").attr("disabled", false);
			$("#stopService").attr("disabled", true);
			$("#remoteControlBtn").attr("disabled", true);
			$("#shareDesktopBtn").attr("disabled", true);
			$("#snapshotBtn").attr("disabled", true);
			$("#recordBtn").attr("disabled", true);
		} else if (dwParam1 == ANYCHAT_AGENT_STATUS_CLOSEED) {
			startServiceTag = false;
			$("#serviceInfoTable tr:eq(3) td:eq(1)").text("未服务");
			$("#startService").attr("disabled", false);
			$("#agentLeave").attr("disabled", false);
			$("#stopService").attr("disabled", true);
			$("#remoteControlBtn").attr("disabled", true);
			$("#shareDesktopBtn").attr("disabled", true);
			$("#snapshotBtn").attr("disabled", true);
			$("#recordBtn").attr("disabled", true);
		}

	}
}

// 坐席服务开始
function OnAnyChatServiceStart(dwAgentId, clientId, dwQueueId, strParam) {
	AddLog('OnAnyChatServiceStart(' + dwAgentId + ',' + clientId + ',' + dwQueueId + ')', LOG_TYPE_EVENT);
	console.log('OnAnyChatServiceStart(' + dwAgentId + ',' + clientId + ',' + dwQueueId + ',' + strParam + ')');
	if (userType == USER_TYPE_AGENT && mSelfUserId == dwAgentId) {
		mTargetUserId = clientId;//客户id		    	
		$("#LOADING_GREY_DIV span").hide();
		userflags = BRAC_ObjectGetIntValue(ANYCHAT_OBJECT_TYPE_CLIENTUSER, mTargetUserId, ANYCHAT_OBJECT_INFO_FLAGS);
		if ((userflags & 16384) != 0) {

			stringtag = BRAC_ObjectGetStringValue(ANYCHAT_OBJECT_TYPE_CLIENTUSER, mTargetUserId, ANYCHAT_OBJECT_INFO_STRINGTAG);
			console.log("用户随路参数tradeNo：" + stringtag + "；");
			//var start_error = BRAC_ObjectControl(ANYCHAT_OBJECT_TYPE_AGENT, mSelfUserId,ANYCHAT_AGENT_CTRL_STARTSERVICE,mTargetUserId);//表明开始服务//var ANYCHAT_AGENT_CTRL_STARTSERVICE=603;	// 当前服务的开始时间，整型
			//AddLog("BRAC_ObjectControl(" + ANYCHAT_OBJECT_TYPE_AGENT+","+mSelfUserId+","+ANYCHAT_AGENT_CTRL_STARTSERVICE + "," + mTargetUserId + ")=" + start_error, LOG_TYPE_API);


			var r = confirm("用户随路参数tradeNo：" + stringtag + "；Userid:" + mTargetUserId + ";");
			if (r == true) {
				console.log("你按下了\"确定\"按钮!");
				var start_error = BRAC_ObjectControl(ANYCHAT_OBJECT_TYPE_AGENT, mSelfUserId, ANYCHAT_AGENT_CTRL_STARTSERVICE, mTargetUserId);//表明开始服务//var ANYCHAT_AGENT_CTRL_STARTSERVICE=603;	// 当前服务的开始时间，整型
				console.log("BRAC_ObjectControl(" + ANYCHAT_OBJECT_TYPE_AGENT + "," + mSelfUserId + "," + ANYCHAT_AGENT_CTRL_STARTSERVICE + "," + mTargetUserId + ")=" + start_error);
				//BRAC_ObjectControl(ANYCHAT_OBJECT_TYPE_AGENT, mSelfUserId, ANYCHAT_AGENT_CTRL_FINISHSERVICE,mTargetUserId);
			} else {
				console.log("你按下了\"取消\"按钮!");
				var reject_error = BRAC_ObjectControl(ANYCHAT_OBJECT_TYPE_AGENT, mSelfUserId, ANYCHAT_AGENT_CTRL_FINISHSERVICE, 100104);//主动传拒绝
				AddLog("BRAC_ObjectControl(" + ANYCHAT_OBJECT_TYPE_AGENT + "," + mSelfUserId + "," + ANYCHAT_AGENT_CTRL_STARTSERVICE + ",100104," + mTargetUserId + ")=" + reject_error, LOG_TYPE_API);
			}

			//var start_error = BRAC_ObjectControl(ANYCHAT_OBJECT_TYPE_AGENT, mSelfUserId,ANYCHAT_AGENT_CTRL_STARTSERVICE,mTargetUserId);//表明开始服务
			//var ANYCHAT_AGENT_CTRL_STARTSERVICE=603;	// 当前服务的开始时间，整型
			//AddLog("BRAC_ObjectControl(" + ANYCHAT_OBJECT_TYPE_AGENT+","+mSelfUserId+","+ANYCHAT_AGENT_CTRL_STARTSERVICE + "," + mTargetUserId + ")=" + start_error, LOG_TYPE_API);

		} else {
			if (isAutoMode == 0) {
				VideoCallRequest(clientId);//呼叫用户
			} else {
				//发送透明通道数据
				var jsonStr = "{\"commandType\":\"videoCall\",\"targetUserId\":" + dwAgentId + ",\"isAutoMode\":1}";
				BRAC_TransBuffer(clientId, jsonStr);
			}
		}
	}
	if (userType == USER_TYPE_CLIENT && mSelfUserId == clientId) {
		mTargetUserId = dwAgentId;
	}
	$("#remoteControlBtn").attr("disabled", false);
}

//队列里没有客户，坐席端处理方式
function OnAnyChatAgentWaitingUser() {
	AddLog('OnAnyChatAgentWaitingUser()', LOG_TYPE_EVENT);
	if ($("#remoteVideoPos").html() == "") {
		$('#LOADING_GREY_DIV').hide();
		startServiceTag = false;
		$("#LOADING_GREY_DIV span").show();
		ForSession('当前队列中已没有客户！', true);
	}
}

function settingClientUserInfo(mUserSettingMode) {
	//选择"服务器端设置"时，先从后台确认用户身份
	if (mUserSettingMode == 2) {
		var Flags = BRAC_ObjectGetIntValue(ANYCHAT_OBJECT_TYPE_CLIENTUSER, mSelfUserId, ANYCHAT_OBJECT_INFO_FLAGS);

		if (Flags == 0) userType = USER_TYPE_CLIENT;

		if (Flags == 2) { userType = USER_TYPE_AGENT; isAutoMode = 0; }
		if (Flags == 18) { userType = USER_TYPE_AGENT; isAutoMode = 1; }
	}

	dwPriority = parseInt($("#dwPrioritySelect option:selected").val());

	switch (userType) {
		case USER_TYPE_CLIENT:
			dwAgentFlags = 0; //客户标识

			mCurrentStatus = CLIENT_STATUS_AREA;

			//设置用户身份信息设置
			InitClientObjectInfo(mSelfUserId, dwAgentFlags, dwPriority, dwAttribute);

			break;

		case USER_TYPE_AGENT:
			currentAgentID = mSelfUserId;

			if (mUserSettingMode == 1) {
				isAutoMode = parseInt($("#routeModeSelect option:selected").val());
				if (isAutoMode == 1) {
					dwAgentFlags = 0x1202; //坐席标识ANYCHAT_OBJECT_FLAGS_AGENT + ANYCHAT_OBJECT_FLAGS_AUTOMODE + ANYCHAT_OBJECT_FLAGS_ONLYSYNCNEED +0x40

				} else {
					dwAgentFlags = 0x1202; //坐席标识ANYCHAT_OBJECT_FLAGS_AGENTE + ANYCHAT_OBJECT_FLAGS_ONLYSYNCNEED + 0x40
				}

				if (routeType == 1) {
					//队列组初始值
					dwAttribute = "";
					var queueGroupValue = "";
					$("input[name='queueCheckBoxGroup']").each(function () {
						if (true == $(this)[0].checked) {
							if (queueGroupValue == "") {
								queueGroupValue = parseInt($(this).attr('value'));
							} else {
								queueGroupValue = queueGroupValue + "," + parseInt($(this).attr('value'));
							}
						}
					});
					queueGroupValue = "[" + queueGroupValue + "]";

					dwAttribute = "{\"flags\":" + dwAgentFlags + ",\"priority\":" + dwPriority + ",\"queuegroups\":" + queueGroupValue + "}";
				}
				else if (routeType == 2) {
					//技能组初始值
					dwAttribute = "";
					var skillGroupValue = "";
					$("input[name='skillCheckBoxGroup']").each(function () {
						if (true == $(this)[0].checked) {
							if (skillGroupValue == "") {
								skillGroupValue = parseInt($(this).attr('value'));
							} else {
								skillGroupValue = skillGroupValue + "," + parseInt($(this).attr('value'));
							}
						}
					});
					skillGroupValue = "[" + skillGroupValue + "]";

					dwAttribute = "{\"flags\":" + dwAgentFlags + ",\"priority\":" + dwPriority + ",\"skillgroups\":" + skillGroupValue + "}";
				}

				//设置坐席身份信息设置
				InitClientObjectInfo(mSelfUserId, dwAgentFlags, dwPriority, dwAttribute);
			}

			mCurrentStatus = AGENT_STATUS_AREA;
			servantName = $("#username").val(); //客服登入账户名

			initAgentVideoForm();

		default:
			break;
	}

}

// 收到录像或拍照完成事件
function OnAnyChatRecordSnapShot(dwUserId, lpFileName, dwParam, bRecordType) {
	AddLog('OnAnyChatRecordSnapShot(' + dwUserId + ',' + lpFileName + ',' + dwParam + ',' + bRecordType + ')', LOG_TYPE_EVENT);
}





